package igou.togogo.controller;

import igou.togogo.bean.EBrand;
import igou.togogo.pojo.EgouResult;
import igou.togogo.service.IBrandService;
import igou.togogo.service.JedisClientService;
import igou.togogo.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/brand")
public class BrandControllerRedis {

    @Autowired
    IBrandService brandService;

    @Autowired
    JedisClientService jedisClientService;

    @RequestMapping("/list")
    @ResponseBody
    public EgouResult getBrandList(){
        //先从缓存中获取品牌列表 如果没有 就从数据库中查询 并加入缓存中
        String json = null;

        try {
            json = jedisClientService.get("brandList");
        } catch (Exception e) {
            e.printStackTrace();
            return EgouResult.build(400,"获取失败");
        }

        List<EBrand> list = null;
        if (json == null){
            list = brandService.selectByExample();
            json = JsonUtils.objectToJson(list);

            try {
                jedisClientService.set("brandList",json);
            } catch (Exception e) {
                e.printStackTrace();
                return EgouResult.build(400,"操作失败");
            }
            //System.out.println("===============从数据库中获取品牌信息================");
        }else {
            list = JsonUtils.jsonToList(json, EBrand.class);
            //System.out.println("===============从缓存中获取品牌信息================");
        }
        return EgouResult.ok(list);
    }
}
